package com.jk.controller.kit;

import cn.org.rapid_framework.generator.GeneratorFacade;
import cn.org.rapid_framework.generator.GeneratorProperties;
import com.jk.dto.JsonResult;
import com.jk.entity.GeneratorEntity;
import com.jk.entity.account.AccUser;
import com.jk.util.JsonUtil;
import com.jk.util.StringUtil;
import com.jk.util.io.ZipUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by yanghuan on 2015/12/28.
 */
@Controller
@RequestMapping("/kit/code")
public class CodeController {

    @RequestMapping("/page")
    public String page() {
        return "kit/code/edit";
    }

    @RequestMapping("/template")
    public String template() {
        return "kit/code/template";
    }

    @RequestMapping(value = "/build")
    @ResponseBody
    public String build(GeneratorEntity entity, HttpServletRequest request) {
        Properties properties = new Properties();
        ServletContext context = request.getSession().getServletContext();
        String template = context.getRealPath("template");
        String outRoot = context.getRealPath("outRoot");
        String zipRoot = context.getRealPath("zipRoot");
        properties.setProperty("basepackage", entity.getBasePackage());
        properties.setProperty("namespace", entity.getNamespace());
        properties.setProperty("outRoot", outRoot);
        properties.setProperty("jdbc.username", entity.getJdbcUsername());
        properties.setProperty("jdbc.password", entity.getJdbcPassword());
        properties.setProperty("jdbc.url", entity.getJdbcUrl());
        properties.setProperty("jdbc.driver", entity.getJdbcDriver());
        GeneratorProperties.setProperties(properties);
        GeneratorFacade generatorFacade = new GeneratorFacade();
        try {
            generatorFacade.deleteOutRootDir();
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "删除历史文件失败"));
        }
        try {
            if (StringUtil.isEmpty(entity.getTableName())) {
                generatorFacade.generateByAllTable(template);
            } else {
                generatorFacade.generateByTable(entity.getTableName(), template);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "生成代码失败，请检查参数是否正确"));
        }
        Subject currentUser = SecurityUtils.getSubject();
        try {
            AccUser accUser = (AccUser) currentUser.getSession().getAttribute("currentUser");
            //根据用户名和当前时间戳生成唯一文件名
            String targetName = accUser.getAccUserName().replaceAll("_", "") + "_" + (new Date()).getTime() + ".zip";
            ZipUtil.compressedFile(outRoot, zipRoot, targetName);
            return JsonUtil.toString(new JsonResult(200, "生成成功", targetName));
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "生成代码压缩包失败"));
        }
    }

    @RequestMapping("/templateTree")
    @ResponseBody
    public String editTemplate(HttpServletRequest request) {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            ServletContext context = request.getSession().getServletContext();
            String template = context.getRealPath("template");
            File file = new File(template);
            File[] files = file.listFiles();
            mapList = getFileTree(files, "template");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonUtil.toString(mapList);
    }

    public List<Map<String, Object>> getFileTree(File[] files, String template) {
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        for (File file : files) {
            String fileName = file.getName();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("fileName", fileName);
            map.put("filePath", template);
            map.put("id", UUID.randomUUID().toString());
            map.put("isDirectory", file.isDirectory());
            if (file.isDirectory()) {
                map.put("children", getFileTree(file.listFiles(), template + File.separatorChar + fileName));
            }
            mapList.add(map);
        }
        return mapList;
    }

    @RequestMapping("/content")
    @ResponseBody
    public String getContent(HttpServletRequest request, String filePath, String fileName) {
        ServletContext context = request.getSession().getServletContext();
        fileName = context.getRealPath(filePath + File.separatorChar + fileName);
        File file = new File(fileName);
        BufferedReader reader = null;
        String result = null;
        try {
            if (file.exists()) {
                InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8");
                reader = new BufferedReader(isr);
                String tempString = "";
                // 一次读入一行，直到读入null为文件结束
                while ((tempString = reader.readLine()) != null) {
                    // 显示行号
                    if (null == result) {
                        result = tempString;
                    } else {
                        result += "\n" + tempString;
                    }
                }
                return JsonUtil.toString(new JsonResult(200, "读取模板成功", result));
            } else {
                return JsonUtil.toString(new JsonResult(201, "模板不存在"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "读取模板失败"));
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/saveTemp")
    @ResponseBody
    public String saveTemp(HttpServletRequest request, String content,
                           String filePath, String fileName,
                           String newFileName, boolean isDirectory) {
        try {
            ServletContext context = request.getSession().getServletContext();
            String fileRealPath = context.getRealPath(filePath + File.separatorChar + fileName);
            String newFileRealPath = context.getRealPath(filePath + File.separatorChar + newFileName);
            File file = new File(fileRealPath);
            if (!file.exists()) {
                return JsonUtil.toString(new JsonResult(201, "模板不存在"));
            }
            if (!isDirectory) {
                // FileWriter 不能指定编码格式 默认为系统编码格式
//                FileWriter fileWriter = new FileWriter(fileRealPath);
//                fileWriter.write(content);
//                fileWriter.flush();
//                fileWriter.close();
                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(fileRealPath), "UTF-8");
                out.write(content);
                out.flush();
                out.close();
            }
            if (!file.getName().equals(newFileName)) {
                file.renameTo(new File(newFileRealPath));
            }
            return JsonUtil.toString(new JsonResult(200, "保存成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.toString(new JsonResult(201, "保存失败"));
        }
    }
}
